import React, { useEffect } from "react";
import { modalPropsType } from "@/constants/types";
import { Form, Modal, Row, Col, Input, Image, DatePicker, Radio } from "antd";
// import { useComponentDidMount } from "@/hooks";
import { fetchActivityOptions } from "../../services";
import XlUpload from "@/components/Form/XlUpload";
import { useModel } from "@umijs/max";
import { fetchLpsLineTagOptions } from "@/pages/ProductManage/services";
import { useRequest } from "ahooks";
import XlSelect from "@/components/Form/XlSelect";
import dayjs from "dayjs";

const {Item} = Form;
const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};
const labelCol = {span: 3};

const UpdateAd = ({title, onCancel, onSubmit, loading, visible, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  // const [pages, setPages] = useState([]);
  // const [slots, setSlots] = useState([]);
  const { getDict } = useModel("dictModel");
  const targetType = getDict("targetType");

  const {data: tagOptions} = useRequest(async () => {
    const res = await fetchLpsLineTagOptions({type: '2'});
    return (res || []).map((v: any) => ({...v, label: v?.name, value: v?.id}));
  });
  const {data: activityOptions} = useRequest(fetchActivityOptions);

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      id: currentRow?.id,
      imageName: res?.image?.[0]?.name,
      imagePath: res?.image?.[0]?.responseUrl,
      name: res?.name,
      title: res?.title,
      targetType: res?.targetType,
      linkTagId: res?.linkTagId,
      linkTagName: tagOptions?.find((op: any) => op?.id === res?.linkTagId)?.name,
      targetPath: res?.targetPath,
      linkActivityId: res?.linkActivityId,
      linkActivityName: activityOptions?.find((op: any) => op?.id === res?.linkActivityId)?.name,
      startTime: res?.time?.[0]?.format('YYYY-MM-DD 00:00:00'),
      endTime: res?.time?.[1]?.format('YYYY-MM-DD 23:59:59')
    });
  }

  
  useEffect(() => {
    if (currentRow) {
      form.setFieldsValue({
        // slotName: currentRow?.slotName,
        image: [{uid: currentRow?.imagePath, url: currentRow?.imageUrl, name: currentRow?.imageName, responseUrl: currentRow?.imagePath}],
        name: currentRow?.name,
        title: currentRow?.title,
        targetType: currentRow?.targetType,
        linkTagId: currentRow?.linkTagId,
        targetPath: currentRow?.targetPath,
        linkActivityId: currentRow?.linkActivityId,
        time: currentRow?.startTime && currentRow?.endTime ? [dayjs(currentRow?.startTime), dayjs(currentRow?.endTime)] : []
      });
    }
  }, [JSON.stringify(currentRow)]);


  // const currPage: any = useMemo(() => {
  //   if (!pages?.length || !currentRow?.pageId) {
  //     return null;
  //   }
  //   return pages?.find((v: any) => v.value === currentRow?.pageId);
  // }, [currentRow?.pageId, JSON.stringify(pages)])

  // useComponentDidMount(() => {
  //   fetchAdPageOptions().then(
  //     res => {
  //       setPages((res || []).map((v: any) => ({...v, label: v?.name, value: v?.id})));
  //     }
  //   )
  // });
  
  return (
    <Modal
      title={title}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      open={visible}
      width="700px"
      maskClosable={false}
    >
      <Form form={form} className="modal-form-padding" labelCol={labelCol}>
        {/* <Item label="广告位" name="slotName" labelCol={{span: 3}}>
          <Input disabled style={{width: 350}} />
        </Item> */}
        <Row gutter={30}>
          <Col span={24}>
            <div>
              <Item label="广告图" rules={[{required: true, message: '请上传广告图'}]} name="image" getValueFromEvent={normFile}>
                <XlUpload max={1} listType="picture-card" uploadParams={{businessCode: 'ad'}} />
              </Item>
              <Item label="广告名称" name="name" rules={[{required: true, message: '请输入广告名称'}]}>
                <Input />
              </Item>
              <Item label="广告标题" name="title" rules={[{required: true, message: '请输入广告标题'}]}>
                <Input />
              </Item>
              <Item label="跳转" name="targetType" rules={[{required: true, message: '请选择落地页类型'}]}>
                <Radio.Group options={targetType} />
              </Item>
              <Item noStyle shouldUpdate={(prev, next) => prev.targetType !== next.targetType}>
                {({getFieldValue}) => {
                  const value = getFieldValue("targetType");
                  return (
                    <Item label="关联标签" name="linkTagId" rules={value === '2' ? [{required: true, message: '请选择关联标签'}] : undefined}>
                    <XlSelect allowClear options={tagOptions} />
                  </Item>
                  );
                }}
              </Item>
              <Item noStyle shouldUpdate={(prev, next) => prev.targetType !== next.targetType}>
                {({getFieldValue}) => {
                  const value = getFieldValue("targetType");
                  return (
                    <Item label="链接地址" name="targetPath" rules={value === "3" ? undefined : [{required: true, message: '请输入链接地址'}]}>
                      <Input />
                    </Item>
                  );
                }}
              </Item>
              <Item noStyle shouldUpdate={(prev, next) => prev.targetType !== next.targetType}>
                {({getFieldValue}) => {
                  const value = getFieldValue("targetType");
                  return (
                    <Item label="关联活动" name="linkActivityId" rules={value === "3" ? [{required: true, message: '请选择关联活动'}] : undefined}>
                      <XlSelect options={activityOptions} dataLabel="name" dataValue="id" />
                    </Item>
                  );
                }}
              </Item>
              <Item label="投放时间" name="time" rules={[{required: true, message: '请选择投放时间'}]}>
                <DatePicker.RangePicker style={{width: 345}} />
              </Item>
            </div>
          </Col>
          {/* <Col span={12}>
            {
              currPage && (
                <Image src={currPage?.imageUrl} width={375} height={667} />
              )
            }
          </Col> */}
        </Row>
      </Form>
    </Modal>
  );
}
export default UpdateAd;